package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice//声明当前类是一个全局异常处理器类
public class GloBalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception ex) {
//        ex.printStackTrace();
        log.error(ex.getMessage());
        String msg = ex.getMessage();
        if (msg.contains("Duplicate entry")) {
            String[] split = msg.split(" ");
            msg = split[9] + "这个名字已经存在，换一个";
            return Result.error(msg);
        }
        return Result.error("对不起,操作失败,请联系管理员");
    }
}
